//
//  ForumViewController.m
//  myCar
//
//  Created by 刘莉 on 14-10-27.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "ForumViewController.h"

#import "WebController.h"
#import "TrendCell.h"
#import "ForumDetailController.h"
#import "TrendCar.h"
#import "UIImageView+WebCache.h"    // 加载图片第三方
#import "Car.h"
#import "BrandCarCell.h"
#import "AIMTableViewIndexBar.h"
#import "WebColor.h"
#import "AFNetworking.h"
#import "MJRefresh.h"
#import "Base.h"
#import "MBProgressHUD.h"

@interface ForumViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, AIMTableViewIndexBarDelegate>

@property (nonatomic, retain)UIScrollView *myScrollView;
@property (nonatomic, retain)UISegmentedControl *mySegment;

@property (nonatomic, retain)UITableView *trendTableView;   //热门
@property (nonatomic, retain)UITableView *brandTableView;   //品牌
@property (nonatomic, retain)UITableView *seriesTableView;  //车型
@property (nonatomic, retain)UITableView *areaTableView;    //地区
@property (nonatomic, retain)UITableView *synthesizeTableView; //综合
@property (nonatomic, retain)NSMutableArray *letterArr;

@property (nonatomic, retain)NSMutableArray *brandNameArr;
@property (nonatomic, retain)NSString *letter;
//@property (nonatomic, retain)NSMutableDictionary *hotDic;
@property (nonatomic, retain)NSMutableArray *hotArr;// 热门的数组  保存热门的信息
@property (nonatomic, retain)AIMTableViewIndexBar *indexBar;  // 索引第三方
@property (nonatomic, retain)NSMutableArray *sectionArr; // 字母数组 如ABC
@property (nonatomic, retain)NSMutableArray *brandChildrenArr;// 每个品牌的子系列数组
@property (nonatomic, retain)NSMutableArray *areaSectionArr; // 地区section数组  保存地区数组中每个字典的key值
@property (nonatomic, retain) NSMutableArray *areaArr; // 地区数组
@property (nonatomic, retain) NSMutableArray *synArr; //  综合数组
@property (nonatomic, retain)NSMutableArray *synSectionArr; // 综合的section数组


@property (nonatomic, retain)UIButton *button; // 开关 button

@property (nonatomic, assign)int countX;

@end

@implementation ForumViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
       
        self.hotArr = [NSMutableArray array];
        self.letterArr = [NSMutableArray array];
        
        self.brandNameArr = [NSMutableArray array];
        self.letter = [NSString string];
        self.sectionArr = [NSMutableArray array];
        
        
        
        
        self.synArr = [NSMutableArray array];
        self.synSectionArr = [NSMutableArray array];
        self.areaArr = [NSMutableArray array];
        self.areaSectionArr = [NSMutableArray array];
    }
    return self;
}

- (void)dealloc
{
    [_button release];
    [_hotArr release];
    
    [_sectionArr release];
   
    [_letter  release];
    [_brandNameArr release];
    [_indexBar release];
    [_myScrollView release];
    [_mySegment release];
    [_trendTableView release];
    [_seriesTableView release];
    [_areaTableView  release];
    [_brandTableView release];
    [_synthesizeTableView release];
    [super dealloc];
}

- (void)strConnection
{
    // 热门页面 数据解析
    MBProgressHUD *hub = [[MBProgressHUD alloc] init];
    [hub setMode:MBProgressHUDModeIndeterminate];
    [hub show:YES];
    [self.view addSubview:hub];
    

    AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
    
    [manager1.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    [manager1 GET:@"http://mrobot.pcauto.com.cn/v3/bbs/hot?pageNo=1&pageSize=20" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSMutableArray *arr = [responseObject objectForKey:@"topicList"];
                for (NSDictionary  *dic in arr) {
                    TrendCar *trendCar = [[TrendCar alloc] initWithDictionary:dic];
                    [self.hotArr addObject:trendCar];
                    [trendCar release];
                }
                [self.trendTableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@".........................2");
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 120, 280, 100)];
                imageView.image = [UIImage imageNamed:@"poNet.jpg"];
                self.trendTableView.backgroundView = imageView;
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"对不起暂无网络" message:@"请检查网络配置" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil, nil];
                [alertView show];
        [imageView release];
    }];
    
    
    NSMutableArray *baseSaveArr = [NSMutableArray array];
    // 车系 地区 综合页面数据解析
    AFHTTPRequestOperationManager *manager2 = [AFHTTPRequestOperationManager manager];
    
    [manager2.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    
    [manager2 GET:@"http://mrobot.pcauto.com.cn/v3/bbs/pcauto_v2_bbs_forum_tree" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *arr =  [[[responseObject objectForKey:@"children"]firstObject] objectForKey:@"children"];
        for (NSDictionary *dic in arr) {
            NSArray *arrMe = [dic objectForKey:@"me"];
            Car *car = [[Car alloc]initWithArray:arrMe];
            self.letter = [arrMe[1] substringToIndex:1];
            if ([[[self.letterArr lastObject]allKeys] containsObject:self.letter]) {
                [[[self.letterArr lastObject] valueForKey:self.letter] addObject:car];
                NSMutableArray *arr = [NSMutableArray array];
                NSMutableDictionary *dicName = [NSMutableDictionary dictionaryWithObject:arr forKey:car.name];
                [[[self.brandNameArr lastObject] valueForKey:self.letter] addObject:dicName];
                
                [car release];
            } else {
                NSMutableArray *carArr = [NSMutableArray arrayWithObject:car];
                NSMutableDictionary *dicCar = [NSMutableDictionary dictionaryWithObject:carArr forKey:self.letter];
                NSMutableArray *childArr = [NSMutableArray array];
                NSMutableDictionary *nameDic = [NSMutableDictionary dictionaryWithObject:childArr forKey:car.name];
                NSMutableArray *meArr = [NSMutableArray arrayWithObject:nameDic];
                NSMutableDictionary *brandDic = [NSMutableDictionary dictionaryWithObject:meArr forKey:self.letter];
                [self.brandNameArr addObject:brandDic];
                [self.letterArr addObject:dicCar];
                [car release];
            }
            NSArray *arrChild = [dic objectForKey:@"children"];
            for (NSDictionary *dic in arrChild) {
                NSArray *arr1 = [dic objectForKey:@"me"];
                Base *base = [[Base alloc]initWithArray:arr1];
                [baseSaveArr addObject:base];
                NSString *str = [[[[self.brandNameArr lastObject]valueForKey:self.letter]lastObject] allKeys][0];
                [[[[[self.brandNameArr lastObject]valueForKey:self.letter]lastObject] valueForKey:str] addObject:base];
                [base release];
            }
        }
        for (NSDictionary *dic in self.letterArr) {  
            [self.sectionArr addObjectsFromArray:[dic allKeys]];
        }
        // 第二个字典 (地区)
        NSMutableArray *areaArr = [[responseObject objectForKey:@"children"][1] objectForKey:@"children"];
        for (NSDictionary *dic in areaArr) {
            NSMutableArray *arr = [NSMutableArray array];
            NSString *str = [dic objectForKey:@"me"][1];
            NSDictionary *areaDic = [NSDictionary dictionaryWithObject:arr forKey:str];
            [self.areaArr addObject:areaDic];
            [self.areaSectionArr addObject:str];
            for (NSDictionary *childDic in [dic objectForKey:@"children"]) {
                NSArray *baseArr = [childDic objectForKey:@"me"];
                Base *base = [[Base alloc]initWithArray:baseArr];
                [[[self.areaArr lastObject] objectForKey:str] addObject:base];
                [baseSaveArr addObject:base];
                [base release];
            }
        }
        // 第三个字典 (综合)
        NSArray *thirdArr = [[responseObject objectForKey:@"children"][2] objectForKey:@"children"];
        for (NSDictionary *childSyn in thirdArr) {
            NSString *str = [childSyn objectForKey:@"me"][1];
            [self.synSectionArr addObject:str];
            NSMutableArray *arr = [NSMutableArray array];
            NSDictionary *meDic = [NSDictionary dictionaryWithObject:arr forKey:str];
            [self.synArr addObject:meDic];
            for (NSDictionary *synDic in [childSyn objectForKey:@"children"]) {
                Base *base = [[Base alloc]initWithArray:[synDic objectForKey:@"me"]];
                [[[self.synArr lastObject] objectForKey:str] addObject:base];
                [baseSaveArr addObject:base];
                [base release];
            }
        }
        [self.indexBar setIndexes:self.sectionArr];
        [self.brandTableView reloadData];
        [self.seriesTableView reloadData];
        [self.areaTableView reloadData];
        [self.synthesizeTableView reloadData];
        [self localSaveWithArray:baseSaveArr];
        [hub removeFromSuperview];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  
    }];
    
    
}

- (void)localSaveWithArray:(NSArray *)arr
{
    
    
   NSString *cachesPath  = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *arrPath = [cachesPath stringByAppendingPathComponent:@"Forum.plist"];
    BOOL arrResult = [NSKeyedArchiver archiveRootObject:arr toFile:arrPath];
  
    NSLog(@"数组写入结果：%d", arrResult);
    if (arrResult == 1) {
        NSLog(@"数组保存成功");
    } else {
        NSLog(@"数组保存失败");
    }
    
}
- (void)setupViews
{
    self.title = @"论坛";
    
    self.navigationController.navigationBar.translucent = NO;
    
    self.mySegment = [[UISegmentedControl alloc] initWithItems:@[@"热门", @"车系", @"地区", @"综合"]];
    self.mySegment.frame = CGRectMake(0, 0, self.view.frame.size.width, 30);
    self.mySegment.selectedSegmentIndex = 0;
    [self.mySegment addTarget:self action:@selector(pageChange:) forControlEvents:UIControlEventValueChanged];
    
    [self.mySegment setBackgroundImage:[UIImage imageNamed:@"segment0.jpg"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [self.mySegment setBackgroundImage:[UIImage imageNamed:@"segment.jpg"] forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
    [self.mySegment setDividerImage:[UIImage imageNamed:@"segment1.jpg"] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    
    
    NSDictionary *colorAttr = [NSDictionary dictionaryWithObject:[UIColor grayColor] forKey:UITextAttributeTextColor];
    [self.mySegment setTitleTextAttributes:colorAttr forState:UIControlStateNormal];
    NSDictionary *colorAttr1 = [NSDictionary dictionaryWithObject:[WebColor dodgerBlue] forKey:UITextAttributeTextColor];
    [self.mySegment setTitleTextAttributes:colorAttr1 forState:UIControlStateSelected];
    
//    [self.mySegment setTintColor:[UIColor blueColor]];
    
    [self.view addSubview:self.mySegment];
    [_mySegment release];
    
    // 底层scrollview
    //  self.automaticallyAdjustsScrollViewInsets = NO;
    self.myScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 30, self.view.bounds.size.width, self.view.bounds.size.height)];
    self.myScrollView.delegate = self;
    self.myScrollView.contentSize = CGSizeMake(self.view.frame.size.width * 4, self.view.frame.size.height);
    self.myScrollView.pagingEnabled = YES;
    self.myScrollView.showsHorizontalScrollIndicator = NO;
    self.myScrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.myScrollView];
    [_myScrollView release];
    
    //论坛热门tableview
    self.trendTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 143) style:UITableViewStylePlain];
    self.trendTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.trendTableView.dataSource = self;
    self.trendTableView.delegate = self;
    [self.myScrollView addSubview:self.trendTableView];
    [self.trendTableView registerClass:[TrendCell class] forCellReuseIdentifier:@"trend"];
    [_trendTableView release];
    self.indexBar = [[AIMTableViewIndexBar alloc]initWithFrame:CGRectMake(self.view.frame.size.width * 2 - 20, 0, 20 , self.view.frame.size.height - 143)];
    self.indexBar.delegate = self;
    [self.myScrollView addSubview:self.indexBar];
    
    //车系品牌tableview
    self.brandTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width - 20, self.view.frame.size.height - 143) style:UITableViewStylePlain];
    self.brandTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.brandTableView.dataSource = self;
    self.brandTableView.delegate = self;
    [self.myScrollView addSubview:self.brandTableView];
    [self.brandTableView registerClass:[BrandCarCell class] forCellReuseIdentifier:@"brand"];
    [_brandTableView release];
    
    //车系车型talbeview
    self.seriesTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.frame.size.width  * 2, 0, self.view.bounds.size.width - 80, self.view.bounds.size.height - 143) style:UITableViewStylePlain];
    self.seriesTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.seriesTableView.dataSource = self;
    self.seriesTableView.delegate = self;
    [self.seriesTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"series"];
    [self.myScrollView addSubview:self.seriesTableView];
    [_seriesTableView release];
    
    //地区tableview
    self.areaTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 2, 0, self.view.frame.size.width, self.view.frame.size.height - 143) style:UITableViewStylePlain];
    self.areaTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.areaTableView.dataSource = self;
    self.areaTableView.delegate = self;
    [self.areaTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"area"];
    [self.myScrollView addSubview:self.areaTableView];
    [_areaTableView release];
    
    //综合页面tableview
    self.synthesizeTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 3, 0, self.view.frame.size.width, self.view.frame.size.height - 143) style:UITableViewStylePlain];
    self.synthesizeTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.synthesizeTableView.dataSource = self;
    self.synthesizeTableView.delegate = self;
    [self.synthesizeTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"syn"];
    [self.myScrollView addSubview:self.synthesizeTableView];
    [_synthesizeTableView release];
    
    self.button = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [self.button setFrame:CGRectMake(self.view.frame.size.width * 2, 140, 20, 30)];
    [self.button setBackgroundImage:[UIImage imageNamed:@"shouqi.png"] forState:(UIControlStateNormal)];
    self.button.hidden = YES;
    [self.button addTarget:self action:@selector(buttonClicked:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.myScrollView addSubview:self.button];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self strConnection];
    [self setupViews];
    [self setupRefresh];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView == self.trendTableView) {
        return 0;
    }
    return 40;
}

// 指定row高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.trendTableView) {
        return 80;
    } else if (tableView == self.brandTableView) {
        return 60;
    } else if (tableView == self.seriesTableView) {
        return 50;
    } else if (tableView == self.areaTableView) {
        return 50;
    } else if (tableView == self.synthesizeTableView) {
        return 50;
    }
    return 60;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView == self.brandTableView) {
        return self.sectionArr[section];
    } else if (tableView == self.areaTableView) {
        return self.areaSectionArr[section];
    } else if(tableView == self.synthesizeTableView) {
        return self.synSectionArr[section];
    }    
    return nil;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == self.brandTableView) {
        return self.letterArr.count;
    } else if (tableView == self.areaTableView) {
        return self.areaSectionArr.count;
    } else if (tableView == self.synthesizeTableView) {
        return self.synSectionArr.count;
    }
    return 1;
}

// 判断当前tableView row个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.trendTableView) {
        return [self.hotArr count];
    } else if(tableView == self.brandTableView) {
        NSArray *arr = [self.letterArr[section] valueForKey:self.sectionArr[section]];
        return arr.count;
    } else if (tableView == self.seriesTableView) {
        
        return self.brandChildrenArr.count;
    } else if (tableView == self.areaTableView) {
        NSString *str = self.areaSectionArr[section];
        NSArray *arr =  [[self.areaArr objectAtIndex:section] objectForKey:str];
        return arr.count;
    } else if (tableView == self.synthesizeTableView) {
        NSString *str = self.synSectionArr[section];
       
        NSArray *arr = [self.synArr[section] objectForKey:str];
        return arr.count;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 热门页面的cell
    if (tableView == self.trendTableView) {
        TrendCell *cell = [tableView dequeueReusableCellWithIdentifier:@"trend"];
        TrendCar *trendCar = [self.hotArr objectAtIndex:indexPath.row];
#warning 图片大小不对
        [cell.trendImage setImageWithURL:[NSURL URLWithString:trendCar.imageStr]];
        cell.titLabel.text = trendCar.titleStr;
        cell.forumLabel.text = trendCar.forumStr;
        NSString *str = [NSString stringWithFormat:@"%@", trendCar.countStr];
        cell.countLabel.text = [str stringByAppendingString:@"楼"];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 60)];
        imageView.image = [UIImage imageNamed:@"cellbg.jpg"];
        cell.backgroundView = imageView;
        return cell;
    } else if (tableView == self.brandTableView) {
        BrandCarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"brand"];
        Car *car = [self.letterArr[indexPath.section] valueForKey:self.sectionArr[indexPath.section]][indexPath.row];
        cell.car = car;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 80)];
        imageView.image = [UIImage imageNamed:@"cellbg.jpg"];
        cell.backgroundView = imageView;
        return cell;
    } else if (tableView == self.seriesTableView) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"series"];
        cell.selectionStyle = 0;
    
        if (indexPath.row <= self.brandChildrenArr.count - 1) {
            Base *base = self.brandChildrenArr[indexPath.row]; //  基类保存的车的信息  如车的名字  和ID
            cell.textLabel.text = base.name;
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 50)];
            imageView.image = [UIImage imageNamed:@"cellbg.jpg"];
            cell.backgroundView = imageView;
        }
     
        return cell;
    } else if (tableView == self.areaTableView) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"area"];
        NSString *str = self.areaSectionArr[indexPath.section];
        
        Base *base = [self.areaArr[indexPath.section] objectForKey:str][indexPath.row];
        cell.textLabel.text = base.name;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 50)];
        imageView.image = [UIImage imageNamed:@"cellbg.jpg"];
        cell.backgroundView = imageView;
        return cell;
    } else if (tableView == self.synthesizeTableView) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"syn"];
        NSString *str = self.synSectionArr[indexPath.section];
        Base *base = [self.synArr[indexPath.section] objectForKey:str][indexPath.row];
        cell.textLabel.text = base.name;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 50)];
        imageView.image = [UIImage imageNamed:@"cellbg.jpg"];
        cell.backgroundView = imageView;
        return cell;
    }
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"reuse"] autorelease];
    }
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 60)];
    imageView.image = [UIImage imageNamed:@"cellbg.jpg"];
    cell.backgroundView = imageView;
    return cell;
}

//点击车系tableViewCell弹出此车论坛页面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 如果点击热门cell 跳转到热门细节页面
    if (tableView == self.trendTableView) {
        WebController *WebVC = [[WebController alloc]init];
        TrendCar *car = self.hotArr[indexPath.row];
        Forum *forum = [[Forum alloc]init];
        forum.topicId = car.IdStr;
        forum.title = car.titleStr;
        WebVC.forum = forum;
        [forum release];
        [self setBackItem:@"返回"];
        [self.navigationController pushViewController:WebVC animated:YES];
        [WebVC release];
    } else if (tableView == self.brandTableView) {
        self.brandChildrenArr = [NSMutableArray array];
        NSString *str = self.sectionArr[indexPath.section];
        Car *car = [self.letterArr[indexPath.section] valueForKey:str][indexPath.row];
        self.brandChildrenArr = [[self.brandNameArr[indexPath.section] valueForKey:str][indexPath.row] valueForKey:car.name];
        [UIView animateWithDuration:0.5 animations:^{
            self.seriesTableView.frame = CGRectMake(self.view.frame.size.width + 90, 0, self.view.frame.size.width - 80, self.view.bounds.size.height - 81);
            [self buttonMove];
             [self.seriesTableView reloadData];
        }];
       
    } else if (tableView == self.seriesTableView) {
        Base *base = self.brandChildrenArr[indexPath.row];
        [self localSaveWithBase:base];
        ForumDetailController *forumDetailVC = [[ForumDetailController alloc]init];
        forumDetailVC.base  = base;
        [self setBackItem:[base.name stringByAppendingString:@"论坛"]];
        [self.navigationController pushViewController:forumDetailVC animated:YES];
        [forumDetailVC release];
    } else if (tableView == self.areaTableView) {
       ForumDetailController *forumDetailVC = [[ForumDetailController alloc]init];
        NSString *sectionStr = self.areaSectionArr[indexPath.section];
        Base *base = [self.areaArr[indexPath.section] objectForKey:sectionStr][indexPath.row];
        [self localSaveWithBase:base];
        NSString *str = base.name;
        forumDetailVC.base = base;
        [self setBackItem:str];
        [self.navigationController pushViewController:forumDetailVC animated:YES];
        [forumDetailVC release];
    } else {
        ForumDetailController *forumDetailVC = [[ForumDetailController alloc]init];
        NSString *str = self.synSectionArr[indexPath.section];
        Base *base = [self.synArr[indexPath.section] objectForKey:str][indexPath.row];
        [self localSaveWithBase:base];
        [self setBackItem:base.name];
        forumDetailVC.base = base;
        [self.navigationController pushViewController:forumDetailVC animated:YES];
        [forumDetailVC release];
    }
}

- (void)localSaveWithBase:(Base *)base
{
    NSString *cachesPath  = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *arrPath = [cachesPath stringByAppendingPathComponent:@"myForum.plist"];
    NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile:arrPath];
    if (arr == nil) {
        NSMutableArray *arrSave = [NSMutableArray arrayWithObject:base];
        [NSKeyedArchiver archiveRootObject:arrSave toFile:arrPath];
    } else {
        NSMutableArray *mArr = [NSMutableArray arrayWithArray:arr];
        if (mArr.count == 4) {
            [mArr removeObjectAtIndex:0];
        }
        for (Base *baseM in mArr) {
            if ([baseM.idNum isEqual:base.idNum]) {
                [mArr removeObject:baseM];
                break;
            }
        }
        [mArr addObject:base];
        BOOL saveResult = [NSKeyedArchiver archiveRootObject:mArr toFile:arrPath];
        NSLog(@"论坛保存结果 %d", saveResult);
    }
}

- (void)buttonMove
{
    self.button.hidden = NO;
    [self.button setFrame:CGRectMake(self.view.frame.size.width + 90, 140 , 20, 40)];
}
/// button 得点击方法
- (void)buttonClicked:(UIButton *)button
{
    
    // 点击button self.seriesView 消息
    [button setFrame:CGRectMake(self.view.frame.size.width * 2, 140, 20, 40)];
     ///button.hidden = YES;
    [UIView animateWithDuration:1 animations:^{
        self.seriesTableView.frame = CGRectMake(self.view.frame.size.width * 2, 0, self.view.frame.size.width - 80, self.view.frame.size.height - 143);
        self.button.hidden = YES;
    }];
}

// 点击segment 改变偏移量
- (void)pageChange:(UISegmentedControl *)segment
{
    self.myScrollView.contentOffset   = CGPointMake(self.view.bounds.size.width * segment.selectedSegmentIndex, 0) ;
}

- (void)viewDidAppear:(BOOL)animated
{
    //self.navigationController.navigationBar.translucent = NO;
    NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,[UIFont boldSystemFontOfSize:20],NSFontAttributeName, nil];
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbackground.jpg"] forBarMetrics:UIBarMetricsDefault];
    
}

#pragma  mark UIScrollView 协议
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (scrollView == self.brandTableView && self.button.hidden == NO  ) {
        self.button.frame = CGRectMake(self.view.frame.size.width * 2, 140, 20, 30);
        
        self.seriesTableView.frame = CGRectMake(self.view.frame.size.width * 2, 0, self.view.frame.size.width - 80, self.view.frame.size.height - 143);
        self.button.hidden = YES;
    }
}

// 判断偏移量 改变segment的index值
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetX = self.myScrollView.contentOffset.x;
    CGFloat width = self.view.bounds.size.width;
    self.mySegment.selectedSegmentIndex  = offsetX / width;
}

- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.trendTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.trendTableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.trendTableView addFooterWithTarget:self action:@selector(footerRereshing)];
    [self.trendTableView footerEndRefreshing];
    //
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.trendTableView.headerPullToRefreshText = @"下拉已刷新...";
    self.trendTableView.headerReleaseToRefreshText = @"松开即可刷新...";
    self.trendTableView.headerRefreshingText = @"刷新中...";
    
    self.trendTableView.footerPullToRefreshText = @"上拉可以加载更多数";
    self.trendTableView.footerReleaseToRefreshText = @"松开马上加载更多数据";
    self.trendTableView.footerRefreshingText = @"加载中";
    
    self.countX = 2;
    NSLog(@"se.countX %d", self.countX);
}
#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        // 刷新表格
        [self.trendTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.trendTableView headerEndRefreshing];
    });
}

- (void)footerRereshing
{
    NSString *str = [NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v3/bbs/hot?pageNo=%d&pageSize=20", self.countX];
    AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
    [manager1.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    [manager1 GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableArray *arr = [responseObject objectForKey:@"topicList"];
        for (NSDictionary  *dic in arr) {
            TrendCar *trendCar = [[TrendCar alloc] initWithDictionary:dic];
            [self.hotArr addObject:trendCar];
            [trendCar release];
        }
        [self.trendTableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.trendTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.trendTableView footerEndRefreshing];
        _countX += 1;
        //        NSLog(@"self.countX %d", self.countX);
    });
    
}

#pragma mark - AIM协议
- (void)tableViewIndexBar:(AIMTableViewIndexBar *)indexBar didSelectSectionAtIndex:(NSInteger)index
{
    [self.brandTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
# pragma mark 设置返回
- (void)setBackItem:(NSString *)str
{
    UIBarButtonItem *backItem = [[[UIBarButtonItem alloc] init] autorelease];
    backItem.title = str;
    backItem.tintColor = [UIColor whiteColor];
    self.navigationItem.backBarButtonItem = backItem;
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
